import axios from "axios"
import router from '../router/index'
import { ElMessage } from 'element-plus'
import cache from '../utils/cache'
import util from '../utils/util'

const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json',
    'Content-Language': util.language()
  },
})
api.interceptors.request.use(request => {
  const user = cache.getObject(cache.keys.loginUser)
  if (user && user.token) {
    request.headers.Token = user.token
  }
  request.data = request.data || {}
  return request
})
let P000002 = false
let P000003 = false
api.interceptors.response.use(res => {
  if (res.status != 200 || !res.data) {
    ElMessage.error(JSON.stringify(res))
    throw res
  }
  if (res.data && res.data.code == 'P000001') {// 参数错误
    ElMessage.error(res.data.message || util.language('参数错误', 'Parameter error'))
    throw res
  }
  if (res.data && res.data.code == 'P000002') {// 登录失效
    cache.setObject(cache.keys.loginUser, null)
    if (P000002 == false) {
      P000002 = true
      ElMessage.error(util.language('未登录或已过期，请重新登录', 'Not logged in or expired, please login again'))
      router.push('/login')
      setTimeout(() => {
        P000002 = false
      }, 1000)
    }
    throw res
  }
  if (res.data && res.data.code == 'P000003') {// 无权限
    if (P000003 == false) {
      P000003 = true
      ElMessage.error(util.language('无权限', 'No permission'))
      setTimeout(() => {
        P000003 = false
      }, 1000)
    }
    throw res
  }
  if (res.data && res.data.code && res.data.code != 'S000001') {
    ElMessage.error(res.data.message || JSON.stringify(res))
    throw res
  }
  if (res.data && res.data.code == 'S000001') {
    return res.data.data
  }
  ElMessage.error(JSON.stringify(res))
  throw res
})

api.baseURL = () => { return '/api' }
api.tokenHeader = () => {
  const result = {}
  const user = cache.getObject(cache.keys.loginUser)
  if (user && user.token) {
    result.Token = user.token
  }
  return result
}
export default api